    //
//  SVoiceRecordButton.m
//  EasyRetail
//
//  Created by Samuel on 10/16/15.
//
//

#define svLOG 1
#if svLOG
#define SVRLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
#define SVRLog(fmt, ...)
#endif

#import "SVoiceRecordButton.h"
#import <AVFoundation/AVFoundation.h>
#import "VoiceConverter.h"
#import "SFlieManage.h"
@interface SVoiceRecordButton ()
@property (strong, nonatomic) AVAudioRecorder* voiceRecorder;
@property (strong, nonatomic) AVAudioPlayer *playController;
@end


@implementation SVoiceRecordButton
{
    NSString *fileName;
}
#pragma mark ＊＊＊＊＊＊＊＊＊＊初始化
-(void)awakeFromNib
{
    [self addTarget:self action:@selector(voiceRecordButtonTapped) forControlEvents:UIControlEventTouchDown];
}
-(void)setIsOpenRecord:(BOOL)isOpenRecord
{
    _isOpenRecord = isOpenRecord;
    if (isOpenRecord == YES) {
        [self addTarget:self action:@selector(voiceRecordButtonRelease) forControlEvents:UIControlEventTouchUpInside];
        [self addTarget:self action:@selector(voiceRecordButtonReleaseOutside) forControlEvents:UIControlEventTouchUpOutside];
        [self addTarget:self action:@selector(voiceRecordButtonDragEnter) forControlEvents:UIControlEventTouchDragEnter];
        [self addTarget:self action:@selector(voiceRecordButtonDragExit) forControlEvents:UIControlEventTouchDragExit];
        self.isOpenPlay = NO;
    }
}


#pragma mark ＊＊＊＊＊＊＊＊＊＊設置
- (void)prepareForRecord
{
    

    /**
     本月文件夹名 时间日期
     */
    NSDateFormatter *voiceDocumentName = [[NSDateFormatter  alloc]init];
    [voiceDocumentName setDateFormat:@"yyyyMM"];
    NSString *voiceDocumentNameString = [NSString stringWithFormat:@"EZR%@",[voiceDocumentName stringFromDate:[NSDate date]]];

    fileName = @"";
    fileName = [[self GetCurrentTimeString]stringByAppendingPathExtension:@"wav"];
    
    NSURL *soundFileURL = [NSURL fileURLWithPath:[[[SFlieManage shareSFlieManage]getDocumentsPathWithCreateAndPath:[DOCUMENTS_VOICE_NAME stringByAppendingPathComponent:voiceDocumentNameString]] stringByAppendingPathComponent:fileName]];

    fileName = [[DOCUMENTS_VOICE_NAME stringByAppendingPathComponent:voiceDocumentNameString]stringByAppendingPathComponent:fileName];
    
    NSError* error;
    if (self.voiceRecorder){
        self.voiceRecorder = nil;
    }
    self.voiceRecorder = [[AVAudioRecorder alloc] initWithURL:soundFileURL
                                                     settings:[VoiceConverter GetAudioRecorderSettingDict]
                                                        error:&error];
    if (!error){
        [self.voiceRecorder prepareToRecord];
    }
    else{
        SVRLog(@"~~~~~   %@",[error description]);
    }
}
#pragma mark - 生成当前时间字符串
- (NSString*)GetCurrentTimeString{
    NSTimeInterval at =[[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970]*1000;
    NSString *voiceString = [NSString stringWithFormat:@"%.f",at];
    return voiceString;
}

#pragma mark - 是否打开自动播放
- (void)setIsOpenPlay:(BOOL)isOpenPlay
{
    _isOpenPlay = isOpenPlay;
    if (isOpenPlay == YES) {
        self.isOpenRecord = NO;
    }
}
#pragma mark ＊＊＊＊＊＊＊＊＊＊按鈕事件
- (void)voiceRecordButtonTapped
{
    if ([self.delegate respondsToSelector:@selector(sVoiceRecordStart:)] && self.isOpenRecord) {
        [self.delegate sVoiceRecordStart:self];
    }
    /**
     *  当前开启的是录制功能
     */
    if (self.isOpenRecord ) {
        [self prepareForRecord];
        AVAudioSession *session = [AVAudioSession sharedInstance];
        [session setCategory:AVAudioSessionCategoryRecord error:nil];
        [session setActive:YES error:nil];
        [self.voiceRecorder record];
    }
    /**
     *  当前开启的是播放功能
     */
    if (self.isOpenPlay) {
        /**
         *  正在播放即停止
         */
        if ([self.playController isPlaying]) {
            [self.playController stop];
            return;
        }
        /**
         *  播放(文件名或data)
         */
        if (self.voiceData) {
            [self playVoiceWithData:self.voiceData];
            return;
        }
        else if(self.voiceName)
        {
            [self playVoiceWithName:self.voiceName];
            return;
        }
        SVRLog(@"請傳遞音頻路徑或數據到：voicePath、voiceData屬性中");
    }
}

- (void)voiceRecordButtonRelease
{
    
    [self.voiceRecorder stop];
    /**
     *  关闭音频组件
     */
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setActive:NO withFlags:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:nil];
    SVRLog(@" 音頻錄製總時長 %f",[self getVoiceTimeWihtPathAndName:fileName]);
    if ([self getVoiceTimeWihtPathAndName:fileName] < ((self.minRecordTime>2)?self.minRecordTime:2.0f))
    {
        /**
         *  删除本地不足2秒的音频文件
         */
        [self deleteVoice:fileName];
        
        if ([self.delegate respondsToSelector:@selector(sVoiceRecord:andRecotdTime:andVoiceName:)]) {
            [self.delegate sVoiceRecord:self andRecotdTime:[self getVoiceTimeWihtPathAndName:fileName] andVoiceName:nil];
        }
    }
    else
    {
        if ([self.delegate respondsToSelector:@selector(sVoiceRecord:andRecotdTime:andVoiceName:)]) {
            [self.delegate sVoiceRecord:self andRecotdTime:[self getVoiceTimeWihtPathAndName:fileName] andVoiceName:fileName];
        }
    }
}

- (void)voiceRecordButtonReleaseOutside
{
    [self.voiceRecorder stop];
    if ([self.delegate respondsToSelector:@selector(sVoiceRecord:andRecotdTime:andVoiceName:)]) {
        [self.delegate sVoiceRecord:self andRecotdTime:100 andVoiceName:nil];
    }
}

- (void)voiceRecordButtonDragEnter
{
    SVRLog(@"voiceRecordButtonDragEnter");
    if ([self.delegate respondsToSelector:@selector(sVoiceRecordInSide:)]) {
        [self.delegate sVoiceRecordInSide:self];
    }
}

- (void)voiceRecordButtonDragExit
{
    SVRLog(@"voiceRecordButtonDragExit");
    if ([self.delegate respondsToSelector:@selector(sVoiceRecordOutSide:)]) {
        [self.delegate sVoiceRecordOutSide:self];
    }
}
#pragma mark ＊＊＊＊＊＊＊＊＊＊音頻操作
#pragma mark - 通过名称检索本地音频进行播放
- (void)playVoiceWithName:(NSString*)name;
{
    NSData* voice = [[SFlieManage shareSFlieManage]readFileWithFileAllPathIncludeName:name];
    /* trimming the voice to small than one Mb控制大小*/
    NSInteger numOfOneMBytes = 1024*1024;
    if ([voice length] > numOfOneMBytes) {
        voice = [NSData dataWithBytesNoCopy:(char*)[[[SFlieManage shareSFlieManage]readFileWithFileAllPathIncludeName:name] bytes]
                                     length:numOfOneMBytes - 1
                               freeWhenDone:NO];
    }
    SVRLog(@"  samuel      %@",voice);
    [self playVoiceWithData:voice];
}
#pragma mark - 通过Data进行播放
- (void)playVoiceWithData:(NSData*)data
{
    NSError *error;
    self.playController = [[AVAudioPlayer alloc] initWithData:data error:&error];
    if (error)
        SVRLog(@"%@", [error localizedDescription]);
    
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    [[AVAudioSession sharedInstance] setActive: YES error: nil];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    
    if (![self.playController isPlaying])
    {
        [self.playController play];
    }
    else
    {
        [self stopVoice];
    }
}
#pragma mark - 停止播放
- (void)stopVoice
{
    if ([self.playController isPlaying])
    {
        [self.playController stop];
    }
}
#pragma mark - 删除本地音频文件
- (void)deleteVoice:(NSString*)path;
{
    if (![[SFlieManage shareSFlieManage]deleteFileWithFileAllPathIncludeName:path]) {
        SVRLog(@"error");
    }
}
#pragma mark - 获取音频时长
- (float)getVoiceTimeWihtName:(NSString*)name;
{
    return [self getVoiceTimeWihtPathAndName:name];
}
- (float)getVoiceTimeWihtPathAndName:(NSString*)path;
{
    AVAudioPlayer* player = [[AVAudioPlayer alloc] initWithData:[[SFlieManage shareSFlieManage]readFileWithFileAllPathIncludeName:path]
                                                          error:nil];
    float time = player.duration;
    return time;
}
@end
